package com.sumainfor.common.util;


import com.alibaba.fastjson.JSONObject;
import com.google.common.reflect.TypeToken;
import com.sumainfor.common.Constants;
import lombok.extern.log4j.Log4j2;
import okhttp3.*;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Log4j2
public class HttpUtil {

    @Autowired
    private OkHttpClient okHttpClient;

    public final OkHttpClient getInstance() {
        return okHttpClient;
    }

    public Call doGet(String url) {
        OkHttpClient okHttpClient = getInstance();
        Request request = new Request.Builder()
                .url(url)
                .build();
        return okHttpClient.newCall(request);
    }


    public Call doPost(String url, RequestBody requestBody) {
        OkHttpClient okHttpClient = getInstance();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .addHeader("X-Tsign-Open-App-Id", Constants.EQB.APP_ID)
                .addHeader("X-Tsign-Open-App-Secret", Constants.EQB.APP_SECRET)
                .build();
        return okHttpClient.newCall(request);
    }

    /**
     * 调用接口获得数据
     *
     * @param url
     * @param params
     * @return
     */
    public JsonResult<Map<String, Object>> doPost(String url, Map<String, Object> params) {
        if (params == null) {
            params = new HashMap<>();
        }
        log.debug("HttpUtil DoPost ===>{}", params);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), JSONObject.toJSONString(params));
        try {
            Response execute = doPost(url, requestBody).execute();
            if (execute.isSuccessful()) {
                String response = execute.body().string();
                log.debug("HttpUtil 请求返回结果: ========>{}", response);
                execute.close();
                if (StringUtils.isNotBlank(response)) {
                    Map<String, Object> data = JSONObject.parseObject(response, new TypeToken<Map<String, Object>>() {
                    }.getType());

                    if (MapUtils.getInteger(data, "errCode").equals(0)) {
                        Object dataResponse = MapUtils.getObject(data, "data");
                        if (data instanceof Map == false) {

                        }
                        return JsonResult.success(dataResponse);
                    } else {
                        return JsonResult.error(MapUtils.getString(data, "msg"));
                    }

                } else {
                    return JsonResult.actionFailure();
                }
            } else {
                return JsonResult.actionFailure();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return JsonResult.actionFailure();
    }

}
